package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.List;

public class EmployeeRealm extends AuthorizingRealm {


    //自定义的数据源,需要根据查询的账号密码进行匹配

    private IEmployeeService employeeService;

    private IRoleService roleService;

    private IPermissionService permissionService;

    public void setRoleService(IRoleService roleService) {
        this.roleService = roleService;
    }

    public void setPermissionService(IPermissionService permissionService) {
        this.permissionService = permissionService;
    }

    public void setEmployeeService(IEmployeeService employeeService) {
        this.employeeService = employeeService;
    }
    //认证是否登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();
        Employee employee = employeeService.selectByUserName(username);
        if(employee!=null){
            if(username.equals(employee.getName())){
                //构造器第三个参数ByteSource.Util.bytes(employee.getName())   就是加盐的意思
                //返回它的(AuthenticationInfo)的实现类
                return new SimpleAuthenticationInfo(employee,employee.getPassword(), ByteSource.Util.bytes(employee.getName()),this.getName());
            }
        }
        return null;
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Employee currentEmployee = (Employee) principalCollection.getPrimaryPrincipal();
        List<String> roles = new ArrayList();
        List<String> permissions = new ArrayList();

        if(currentEmployee.isAdmin()){
            //这里需要换成表达式不然,如果没有加载的话是没有新增的使用权限
            info.addRole("admin");
            info.addStringPermission("*:*");
            return info;
        }
        roles = roleService.queryRolesByEmployeeId(currentEmployee.getId());
        permissions = permissionService.queryExpressionsByEmployeeId(currentEmployee.getId());
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;
    }

}
